package com.example.restaurantclient.Activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.restaurantclient.Adapter.CustomSearchView;
import com.example.restaurantclient.Adapter.SearchAdapter;
import com.example.restaurantclient.Bubble.SearchFlowLayout;
import com.example.restaurantclient.ConfigUtil.ConfigUtil;
import com.example.restaurantclient.Entities.SearchResult;
import com.example.restaurantclient.Fragment.HomeFragment;
import com.example.restaurantclient.R;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SearchActivity extends AppCompatActivity implements CustomSearchView.SearchViewListener {
    private Button btnDeletehistory;
    private TextView tvCancel;
    private CustomSearchView customSearchView;
    private SearchFlowLayout flowLayoutHistory;
    private SearchFlowLayout flowLayoutHot;
    private List<String> histories=new ArrayList<>();//搜索记录
    private ListView lvResults; //搜索结果列表
    private ArrayAdapter<String> autoCompleteAdapter;//自动补全
    private List<SearchResult> resultData; //搜索结果数据
    private List<SearchResult> dbData=new ArrayList<>();//数据库的结果
    private OkHttpClient okHttpClient;
    private List<String> mHotList = new ArrayList<>();//热搜
    //搜索过程中自动补全数据
    private List<String> autoCompleteData;
    //默认提示框显示项的个数
    private static int DEFAULT_HINT_SIZE = 5;

    //搜索结果列表adapter
    private SearchAdapter resultAdapter;
    //提示框显示项的个数
    private static int hintSize = DEFAULT_HINT_SIZE;
    //设置提示框显示项的个数
    public static void setHintSize(int hintSize) {
        SearchActivity.hintSize = hintSize;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        btnDeletehistory=findViewById(R.id.btn_delete_history);
        customSearchView=findViewById(R.id.custom_searchview);
        okHttpClient=new OkHttpClient();
        tvCancel=findViewById(R.id.tv_search_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(SearchActivity.this, FragmentActivity.class));
            }
        });
        //删除历史记录
        btnDeletehistory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                deleteAllHistory();
            }
        });
        getHistoryData();//获取历史记录
        initChildViews();//初始化历史搜索记录
        initData();//初始化数据
        initViews();//初始化控件
        initHotViews();//初始化热词搜索记录
    }

    private void initHotViews() {
        flowLayoutHot= (SearchFlowLayout) findViewById(R.id.flowkayout_hot);
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        lp.leftMargin = 10;
        lp.rightMargin = 10;
        lp.topMargin = 10;
        lp.bottomMargin = 10;

        for(int i = 0; i < mHotList.size(); i ++){
            TextView view = new TextView(this);
            view.setText(mHotList.get(i));
            view.setTextColor(Color.BLACK);
            view.setPadding(10,10,10,10);
            view.setBackgroundResource(R.drawable.arc_line_white);
            final String text=mHotList.get(i);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onSearch(text);
                }
            });
            flowLayoutHot.addView(view,lp);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //注册事件订阅者
        EventBus.getDefault().register(this);
    }
    //注销订阅者
    @Override
    protected void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    //处理事件的方法 强制要求在主线程执行
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleSearchResult(String result){
        if(result.equals("result")){
            //更新搜索结果
            resultAdapter.notifyDataSetChanged();
        }else if (result.equals("history")){
            initChildViews();
        }else if(result.equals("delete")){
            flowLayoutHistory.removeAllViews();
        } else{
            ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.leftMargin = 10;
            lp.rightMargin = 10;
            lp.topMargin = 10;
            lp.bottomMargin = 10;

            TextView view = new TextView(this);
            view.setText(result);
            view.setTextColor(Color.BLACK);
            view.setPadding(10, 10, 10, 10);
            view.setBackgroundResource(R.drawable.arc_line_white);
            flowLayoutHistory.addView(view,0,lp);
        }
    }
    //初始化搜索数据
    private void initData() {
        getDbData();

        //初始化热搜版数据
        getHintData();
        //初始化自动补全数据
        getAutoCompleteData(null);
        //初始化搜索结果数据
        getResultData(null);
    }

    private void getDbData() {
        if(dbData!=null&&dbData.size()>0){
            dbData.clear();
        }
        SearchResult result1=new SearchResult("安心吃套餐","dish_1","anxinchitaocan","好评度70% '味道正，很下饭'");
        dbData.add(result1);
        SearchResult result2=new SearchResult("银耳羹","dish_2","yinergeng","好评度70% '味道正，很下饭'");
        dbData.add(result2);
        SearchResult result0=new SearchResult("糖醋里脊","dish_3","tangculiji","好评度70% '味道正，很下饭'");
        dbData.add(result0);
        SearchResult result3=new SearchResult("酸辣土豆丝","dish_4","suanlatudousi","好评度70% '味道正，很下饭'");
        dbData.add(result3);
        SearchResult result4=new SearchResult("小鹌鹑","dish_5","xiaoanchun","好评度70% '味道正，很下饭'");
        dbData.add(result4);
        SearchResult result5=new SearchResult("番茄炒蛋","dish_6","fanqiechaodan","好评度70% '味道正，很下饭'");
        dbData.add(result5);
        SearchResult result6=new SearchResult("鱼香肉丝","dish_7","yuxiangrousi","好评度95% '非常香，以后会经常光顾'");
        dbData.add(result6);
        SearchResult result7=new SearchResult("干锅花菜","dish_8","ganguohuacai","好评度88% '东西多，还好吃'");
        dbData.add(result7);
        SearchResult result8=new SearchResult("梅菜扣肉","dish_9","meicaikourou","好评度93% '味道正，很下饭'");
        dbData.add(result8);
        SearchResult result9=new SearchResult("干锅腐竹","dish_10","ganguofuzhu","好评度100% '干锅腐竹百吃不厌'");
        dbData.add(result9);
        SearchResult result10=new SearchResult("酸菜鱼","dish_12","suancaiyu","好评度95% '味道正，很下饭'");
        dbData.add(result10);
        SearchResult result11=new SearchResult("巴西烤肉","dish_11","baxikaorou","好评度95% '肉多好吃，超级下饭'");
        dbData.add(result11);


    }

    private void initViews() {
        lvResults = (ListView) findViewById(R.id.search_results);
        //设置监听
        customSearchView.setSearchViewListener(this);
        //设置adapter
        customSearchView.setAutoCompleteAdapter(autoCompleteAdapter);

    }
    private void getAutoCompleteData(String text) {
        if (autoCompleteData == null) {
            //初始化
            autoCompleteData = new ArrayList<>(hintSize);
        } else {
            autoCompleteData = new ArrayList<>(hintSize);

//             根据text 获取auto data
            autoCompleteData.clear();
            for (int i = 0, count = 0; i < dbData.size()
                    && count < hintSize; i++) {
                if (dbData.get(i).getName().contains(text.trim())|| dbData.get(i).getEnglishName().contains(text.trim())) {
                    autoCompleteData.add(dbData.get(i).getName());
                    count++;
                }
            }
        }
        if (autoCompleteAdapter == null) {
            autoCompleteAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, autoCompleteData);
        } else {
            autoCompleteAdapter.clear();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                autoCompleteAdapter.addAll(autoCompleteData);
            }
            autoCompleteAdapter.notifyDataSetChanged();
        }
    }
    private void getHintData() {
        //设置热搜数据
        String[] tags={"安心吃套餐","银耳羹","巴西烤肉","酸菜鱼"};
        mHotList.clear();
        mHotList.addAll(Arrays.asList(tags));
    }
    private void deleteAllHistory() {
        //传入userid
        //LoginActivity.member.getMemberId()
        /*RequestBody requestBody = RequestBody.create(MediaType.parse(
                "text/plain;charset=utf-8"),"1");
        Request request=new Request.Builder()
                .post(requestBody)
                .url(ConfigUtil.SERVER_ADDR+"deleteAllHistory")
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure","deleteAllHistory发生错误");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取轮播图列表数据
                String json=response.body().string();
                if (json.equals("delete")){
                    histories.clear();
                    EventBus.getDefault().post("delete");
                }
            }
        });*/
        histories.clear();
        EventBus.getDefault().post("delete");
    }
    private void getHistoryData() {
        //传入memeberid
        /*RequestBody requestBody = RequestBody.create(MediaType.parse(
                "text/plain;charset=utf-8"),"1");
        Request request=new Request.Builder()
                .post(requestBody)
                .url(ConfigUtil.SERVER_ADDR+"ClientSearchHistories")
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure","banner发生错误");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取轮播图列表数据
                String json=response.body().string();
                Type type=new TypeToken<List<String>>(){}.getType();//获取实际类型
                List<String> list=new Gson().fromJson(json,type);
                //修改数据源
                histories.addAll(list);
                //使用EventBus 发布事件更新adapter
                EventBus.getDefault().post("history");
            }
        });*/
        histories.add("糖醋里脊");
        EventBus.getDefault().post("history");
    }
    //初始化历史搜索记录数据view
    private void initChildViews() {
        flowLayoutHistory= (SearchFlowLayout) findViewById(R.id.flowkayout_history);
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = 10;
        lp.rightMargin = 10;
        lp.topMargin = 10;
        lp.bottomMargin = 10;

        for(int i = 0; i < histories.size(); i ++){
            TextView view = new TextView(this);
            view.setText(histories.get(i));
            view.setTextColor(Color.BLACK);
            view.setPadding(10,10,10,10);
            view.setBackgroundResource(R.drawable.arc_line_white);
            final String text=histories.get(i);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onSearch(text);
                }
            });
            flowLayoutHistory.addView(view,lp);
        }
    }
    //搜索后加入历史记录
    private void addHistoryData(final String text) {
        /*String userId=LoginActivity.member.getMemberId()+"";
        FormBody formBody=new FormBody.Builder()
                .add("userId",userId)
                .add("history",text)
                .build();
        Request request=new Request.Builder()
                .post(formBody)
                .url(ConfigUtil.SERVER_ADDR+"ClientAddHistory")
                .build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure","banner发生错误");
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取轮播图列表数据
                String str=response.body().string();
                if(str.equals("insert")){
                    EventBus.getDefault().post(text);
                }
            }
        });*/
        if(!histories.contains(text)){
            EventBus.getDefault().post(text);
            histories.add(text);
        }

    }

    /**
     * 当搜索框 文本改变时 触发的回调 ,更新自动补全数据
     * @param text
     */
    @Override
    public void onRefreshAutoComplete(String text) {
        //更新数据
        getAutoCompleteData(text);
    }

    /**
     * 点击搜索键时edit text触发的回调
     * @param text
     */
    @Override
    public void onSearch(String text) {
        //更新result数据
        getResultData(text);

        //第一次获取结果 还未配置适配器
        if (lvResults.getAdapter() == null) {
            //获取搜索数据 设置适配器
            lvResults.setAdapter(resultAdapter);
        } else {
            //更新搜索数据
            resultAdapter.notifyDataSetChanged();
        }
        if(resultData!=null&&resultData.size()>0){
            lvResults.setVisibility(View.VISIBLE);
            customSearchView.setmResultAdapter(resultAdapter);
            Toast.makeText(this, "完成搜索", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "未搜索到", Toast.LENGTH_SHORT).show();
            lvResults.setVisibility(View.GONE);
        }
        addHistoryData(text);

    }

    @Override
    public void onSearchAgain(String text) {
        if (text.equals("")){
            if (resultAdapter!=null){
                resultData.clear();
                lvResults.setVisibility(View.GONE);
                resultAdapter.notifyDataSetChanged();

            }
        }
    }

    private void getResultData(String text) {
        if (resultData == null) {
            // 初始化
            resultData = new ArrayList<>();
        } else {
            resultData.clear();
            for (int i = 0; i < dbData.size(); i++) {
                if(!text.equals("")&&text!=null){
                    if (dbData.get(i).getName().contains(text.trim())) {
                        resultData.add(dbData.get(i));
                    }
                }
            }
        }
        if (resultAdapter == null) {
            resultAdapter = new SearchAdapter(this, resultData, R.layout.item_search_result);
        } else {
            resultAdapter.notifyDataSetChanged();
        }
    }
}